package com.ruoyi.cat.service.impl;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.ruoyi.cat.domain.CatArticlegiftTable;
import com.ruoyi.cat.domain.CatArticletaskTable;
import com.ruoyi.cat.domain.CatOutsiderealmTable;
import com.ruoyi.cat.domain.CatTradedetailTable;
import com.ruoyi.cat.domain.DTO.ArticletaskDTO;
import com.ruoyi.cat.domain.DTO.LatestTaskDTO;
import com.ruoyi.cat.domain.VO.DataScreeningVO;
import com.ruoyi.cat.domain.VO.IncreaseVO;
import com.ruoyi.cat.mapper.CatArticletaskTableMapper;
import com.ruoyi.cat.service.*;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OrderUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.Base64Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

/**
 * 文章任务Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-24
 */
@Service
@Slf4j
public class CatArticletaskTableServiceImpl implements ICatArticletaskTableService
{
    @Autowired
    private CatArticletaskTableMapper catArticletaskTableMapper;


    @Autowired
    private ICatArticlegiftTableService iCatArticlegiftTableService;

    @Autowired
    private ICatTradedetailTableService iCatTradedetailTableService;

    @Autowired
    private ICatOutsiderealmTableService iCatOutsiderealmTableService;

    @Autowired
    private ICatIprecordTableService catIprecordTableService;

    /**
     * 查询文章任务
     * 
     * @param id 文章任务主键
     * @return 文章任务
     */
    @Override
    public CatArticletaskTable selectCatArticletaskTableById(Long id)
    {
        CatArticletaskTable catArticletaskTable = catArticletaskTableMapper.selectCatArticletaskTableById(id);
        if (catArticletaskTable != null) {
            CatArticlegiftTable catArticlegiftTable = new CatArticlegiftTable();
            catArticlegiftTable.setArticleId(catArticletaskTable.getId());
            catArticletaskTable.setCatArticlegiftTableList(iCatArticlegiftTableService.selectCatArticlegiftTableList(catArticlegiftTable));
        }
        return catArticletaskTable;
    }

    @Override
    public List<CatArticletaskTable> getTimeData() {
        return catArticletaskTableMapper.getTimeData();
    }

    @Override
    public CatArticletaskTable selectArticletaskById(Long id) {
        CatArticletaskTable catArticletaskTable = catArticletaskTableMapper.selectCatArticletaskTableById(id);

        return catArticletaskTable;
    }

    @Override
    public CatArticletaskTable selectCatArticletaskContentTableById(Long id)
    {
        CatArticletaskTable catArticletaskTable = catArticletaskTableMapper.selectCatArticletaskContentTableById(id);
        if (catArticletaskTable != null) {
            CatArticlegiftTable catArticlegiftTable = new CatArticlegiftTable();
            catArticlegiftTable.setArticleId(catArticletaskTable.getId());
            catArticletaskTable.setCatArticlegiftTableList(iCatArticlegiftTableService.selectCatArticlegiftTableList(catArticlegiftTable));
        }
        return catArticletaskTable;
    }

    @Override
    public ArticletaskDTO selectCatArticletaskById(Long id) {
        ArticletaskDTO catArticletaskTable = catArticletaskTableMapper.selectCatArticletaskById(id);
        if (catArticletaskTable != null) {
            DataScreeningVO dataScreeningVO = new DataScreeningVO();
            dataScreeningVO.setActivityId(catArticletaskTable.getId());
            dataScreeningVO.setType("1");
            catArticletaskTable.setReadingVolume(catIprecordTableService.getIprecordTableBy(dataScreeningVO));
            CatArticlegiftTable catArticlegiftTable = new CatArticlegiftTable();
            catArticlegiftTable.setArticleId(catArticletaskTable.getId());
            catArticletaskTable.setCatArticlegiftTableList(iCatArticlegiftTableService.selectCatArticlegiftTableList(catArticlegiftTable));
        }
        return catArticletaskTable;
    }

    /**
     * 查询文章任务列表
     * 
     * @param catArticletaskTable 文章任务
     * @return 文章任务
     */
    @Override
    public List<CatArticletaskTable> selectCatArticletaskTableList(CatArticletaskTable catArticletaskTable)
    {
        List<CatArticletaskTable> list = catArticletaskTableMapper.selectCatArticletaskTableList(catArticletaskTable);
        list.stream().forEach(e -> {
            if (e.getDomainName() != null) {
                CatOutsiderealmTable catOutsiderealmTable = iCatOutsiderealmTableService.selectCatOutsiderealmByDomainName(e.getDomainName());

                if (catOutsiderealmTable != null) {
                    if (StringUtils.isNotEmpty(catOutsiderealmTable.getOutSideRealmId())){
                        e.setQrCode(catOutsiderealmTable.getOutSideRealmId());
                    }
                    if (StringUtils.isNotEmpty(catOutsiderealmTable.getDomainName())){
                        e.setDomainName(catOutsiderealmTable.getDomainName());
                       // e.setQrCode(catOutsiderealmTable.getDomainName());
                    }
                }
             }
            CatTradedetailTable catTradedetailTable =  iCatTradedetailTableService.getTradedetailActivityId(e.getId());
            if (catTradedetailTable!= null) {
                e.setStatus(catTradedetailTable.getStatus());
            }else{
                e.setStatus("0");
            }
        });
        return list;
    }

    /**
     * 新增文章任务
     * 
     * @param catArticletaskTable 文章任务
     * @return 结果
     */
    @Override
    public int insertCatArticletaskTable(CatArticletaskTable catArticletaskTable)
    {
        catArticletaskTable.setCreateTime(DateUtils.getNowDate());
        catArticletaskTable.setArticleExamine("2");
        if (StringUtils.isEmpty(catArticletaskTable.getOrderNo())){
            catArticletaskTable.setArticleState("2");
        }
        int i =catArticletaskTableMapper.insertCatArticletaskTable(catArticletaskTable);
        if (null !=catArticletaskTable.getCatArticlegiftTableList()) {
            catArticletaskTable.getCatArticlegiftTableList().forEach(catArticlegiftTable -> {
                catArticlegiftTable.setArticleId(catArticletaskTable.getId());
                iCatArticlegiftTableService.insertCatArticlegiftTable(catArticlegiftTable);
            });
        }
        if (StringUtils.isNotEmpty(catArticletaskTable.getOrderNo())){
            CatTradedetailTable catTradedetailTable = new  CatTradedetailTable();
            catTradedetailTable.setOrderNo(catArticletaskTable.getOrderNo());
            catTradedetailTable.setActivityId(catArticletaskTable.getId());
            CatArticletaskTable catArticletaskTable1 = new CatArticletaskTable();
            catArticletaskTable1.setId(catArticletaskTable.getId());
            catArticletaskTable1.setArticleState("2");
            catArticletaskTableMapper.updateCatArticletaskTable(catArticletaskTable1);
            iCatTradedetailTableService.updateCatTradedetailTableOrderNo(catTradedetailTable);
        }
        //支付订单
        CatTradedetailTable catTradedetailTable = new CatTradedetailTable();
        String orderNo = OrderUtil.makeOrderNo();
        catTradedetailTable.setOrderNo(orderNo);
        catTradedetailTable.setActivityId(catArticletaskTable.getId());
        catTradedetailTable.setStatus("1");
        catTradedetailTable.setTradeType("1");
        catTradedetailTable.setType("1");
        iCatTradedetailTableService.insertCatTradedetailTable(catTradedetailTable);
        return i;
    }

    @Override
    public int insertCatArticletaskTableOutside(CatArticletaskTable catArticletaskTable) {
        int i =catArticletaskTableMapper.insertCatArticletaskTable(catArticletaskTable);

        if (null !=catArticletaskTable.getCatArticlegiftTableList()) {
            catArticletaskTable.getCatArticlegiftTableList().forEach(catArticlegiftTable -> {
                catArticlegiftTable.setArticleId(catArticletaskTable.getId());
                iCatArticlegiftTableService.insertCatArticlegiftTable(catArticlegiftTable);
            });
        }
        updateBoday(catArticletaskTable);
        return i;
    }

    public void updateBoday(CatArticletaskTable catArticletaskTable) {
        try {
            // 1. 读取模板文件
            Resource resource = new ClassPathResource("templates/link.html");
            String template = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8);

            // 2. 替换文章内容
            String articleContent = catArticletaskTable.getArticleContent();
            // 2. 替换文章内容、标题和承办方
            String articleTitle = catArticletaskTable.getArticleTitle();
            String organizer = catArticletaskTable.getOrganizer();
            /*String modifiedHtml = template.replace(
                    "<div id=\"content\"></div>",
                    "<div id=\"content\">" + articleContent + "</div>"
            );*/

            String modifiedHtml = template
                    .replace("<div id=\"content\"></div>",
                            "<div id=\"content\">" + articleContent + "</div>")
                    .replace("<h2 id=\"title\"></h2>",
                            "<h2 id=\"title\">" + articleTitle + "</h2>")
                    .replace("<span id=\"organizer\"></span>",
                            "<span id=\"organizer\">" + organizer + "</span>");

            // 3. 设置文件路径
            String baseDir = "/home/cat/wenzhang";
            Path outputDir = Paths.get(baseDir);

            // 4. 创建目录（如果不存在）
            if (!Files.exists(outputDir)) {
                Files.createDirectories(outputDir);
            }

            String fileName = "article_" + Base64Util.encryptNumber(catArticletaskTable.getId()+"") + ".html";
            Path filePath = outputDir.resolve(fileName);

            // 5. 如果文件存在，先删除旧文件
            if (Files.exists(filePath)) {
                try {
                    Files.delete(filePath);
                } catch (IOException e) {
                    throw new RuntimeException("删除旧文件失败: " + filePath, e);
                }
            }

            // 6. 写入新文件
            try {
                Files.write(filePath, modifiedHtml.getBytes(StandardCharsets.UTF_8));
            } catch (IOException e) {
                throw new RuntimeException("写入新文件失败: " + filePath, e);
            }

        } catch (Exception e) {
            throw new RuntimeException("生成HTML文件失败", e);
        }
    }

    @Override
    public int insertCatArticletaskTableApi(CatArticletaskTable catArticletaskTable) {
        catArticletaskTable.setInvitationSource("1");
        catArticletaskTable.setCreateTime(DateUtils.getNowDate());
        if (StringUtils.isEmpty(catArticletaskTable.getOrderNo())){
            catArticletaskTable.setArticleState("2");
        }
        int i =catArticletaskTableMapper.insertCatArticletaskTable(catArticletaskTable);
        if (null !=catArticletaskTable.getCatArticlegiftTableList()) {
            catArticletaskTable.getCatArticlegiftTableList().forEach(catArticlegiftTable -> {
                catArticlegiftTable.setArticleId(catArticletaskTable.getId());
                iCatArticlegiftTableService.insertCatArticlegiftTable(catArticlegiftTable);
            });
        }
        if (StringUtils.isNotEmpty(catArticletaskTable.getOrderNo())){
            CatTradedetailTable catTradedetailTable = new  CatTradedetailTable();
            catTradedetailTable.setOrderNo(catArticletaskTable.getOrderNo());
            catTradedetailTable.setActivityId(catArticletaskTable.getId());
            CatArticletaskTable catArticletaskTable1 = new CatArticletaskTable();
            catArticletaskTable1.setId(catArticletaskTable.getId());
            catArticletaskTable1.setArticleState("2");
            catArticletaskTableMapper.updateCatArticletaskTable(catArticletaskTable1);
            iCatTradedetailTableService.updateCatTradedetailTableOrderNo(catTradedetailTable);
        }
        updateBoday(catArticletaskTable);
        return i;
    }

    /**
     * 修改文章任务
     * 
     * @param catArticletaskTable 文章任务
     * @return 结果
     */
    @Override
    public int updateCatArticletaskTable(CatArticletaskTable catArticletaskTable)
    {
        catArticletaskTable.setCreateTime(DateUtils.getNowDate());
        ArticletaskDTO articletaskDTO = catArticletaskTableMapper.selectCatArticletaskById(catArticletaskTable.getId());
        Date originalEndTime = articletaskDTO.getEndTime();
        Date newEndTime = catArticletaskTable.getEndTime();
        Date currentTime = new Date();
        if (newEndTime != null &&
                (originalEndTime == null || !originalEndTime.equals(newEndTime)) &&
                newEndTime.after(currentTime)) {

            // 检查文章当前状态是否为"结束"
            String currentStatus = articletaskDTO.getArticleExamine();
            if ("3".equals(currentStatus)) { // 假设"3"表示已结束状态
                log.info("文章ID: {} 的结束日期已修改且大于当前时间，将状态从\"结束\"更新为\"进行中\"", catArticletaskTable.getId());

                // 更新文章状态为"进行中"
                catArticletaskTable.setArticleExamine("2"); // 假设"2"表示进行中状态
                int result = catArticletaskTableMapper.updateCatArticletaskTable(catArticletaskTable);

                log.info("文章状态更新结果: {}", result > 0 ? "成功" : "失败");
            } else {
                log.info("文章ID: {} 当前状态不是\"结束\"，无需更新状态", catArticletaskTable.getId());
            }
        } else {
            log.info("文章ID: {} 的结束日期未修改或不大于当前时间，不更新状态", catArticletaskTable.getId());
        }
        int i =catArticletaskTableMapper.updateCatArticletaskTable(catArticletaskTable);
        iCatArticlegiftTableService.deleteCatArticlegiftTableById(catArticletaskTable.getId());
        if (null != catArticletaskTable.getCatArticlegiftTableList()) {
            catArticletaskTable.getCatArticlegiftTableList().forEach(catArticlegiftTable -> {
                catArticlegiftTable.setArticleId(catArticletaskTable.getId());
                iCatArticlegiftTableService.insertCatArticlegiftTable(catArticlegiftTable);
            });
        }
        updateBoday(catArticletaskTable);
        return i;
    }

    @Override
    public int updateVisitors(CatArticletaskTable catArticletaskTable)
    {
        catArticletaskTable.setCreateTime(DateUtils.getNowDate());
        int i =catArticletaskTableMapper.updateCatArticletaskTable(catArticletaskTable);
     //   updateBoday(catArticletaskTable);
        return i;
    }

    @Override
    public int updateAdvertTime(CatArticletaskTable catArticletaskTable) {

        return catArticletaskTableMapper.updateCatArticletaskTable(catArticletaskTable);
    }

    /**
     * 批量删除文章任务
     * 
     * @param ids 需要删除的文章任务主键
     * @return 结果
     */
    @Override
    public int deleteCatArticletaskTableByIds(Long[] ids)
    {
        return catArticletaskTableMapper.deleteCatArticletaskTableByIds(ids);
    }

    /**
     * 删除文章任务信息
     * 
     * @param id 文章任务主键
     * @return 结果
     */
    @Override
    public int deleteCatArticletaskTableById(Long id)
    {
        return catArticletaskTableMapper.deleteCatArticletaskTableById(id);
    }

    @Override
    public List<ArticletaskDTO> getActivityListApiShare() {
        return catArticletaskTableMapper.getActivityListApiShare();
    }

    @Override
    public List<CatArticletaskTable> getArticletask() {
        return catArticletaskTableMapper.getArticletask();
    }

    @Override
    public List<CatArticletaskTable> selectCatArticletaskData(CatArticletaskTable catArticletaskTable) {
        return catArticletaskTableMapper.selectCatArticletaskData(catArticletaskTable);
    }

    @Override
    public List<LatestTaskDTO> getLatestTasks() {
        return catArticletaskTableMapper.getLatestTasks();
    }

    @Override
    public int updateTable(CatArticletaskTable catArticletaskTable) {
        return catArticletaskTableMapper.updateTable(catArticletaskTable);
    }

    @Override
    public AjaxResult increaseValue(IncreaseVO increaseVO) {

        CatTradedetailTable catTradedetailTable =    iCatTradedetailTableService.selectCatTradedetailTableByOrderNo(increaseVO.getOrderNo());
        if (catTradedetailTable == null) {
           return AjaxResult.error("订单不存在");
        }else{
            if (catTradedetailTable.getStatus().equals("0")){
                return AjaxResult.error("订单未支付成功");
            }
        }
        CatArticletaskTable catArticletaskTable = new CatArticletaskTable();
        catArticletaskTable.setId(increaseVO.getId());
        catArticletaskTable.setTargetNum(increaseVO.getTargetNum());
        return AjaxResult.success(catArticletaskTableMapper.updateTable(catArticletaskTable));
    }

    @Override
    public AjaxResult updateBody(Long id) {
        CatArticletaskTable catArticletaskTable = catArticletaskTableMapper.selectCatArticletaskContentTableById(id);
        try{
            updateBoday(catArticletaskTable);
            return AjaxResult.success("生成页面成功");
        }catch (Exception e){
            return AjaxResult.error("生成页面错误");
        }
    }

    @Override
    public List<CatArticletaskTable> getArticletaskTask() {
        return catArticletaskTableMapper.getArticletaskTask();
    }

    @Override
    public List<LatestTaskDTO> getArticletaskTaskHome() {
        return catArticletaskTableMapper.getArticletaskTaskHome();
    }
}
